package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spring.web.json.Json;

import javax.print.DocFlavor;
import java.util.Arrays;
import java.util.Locale;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-20
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;



    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        try {
            //发起入住申请
            //校验老人是否入住（根据身份证校验）
            //创建查询条件
            LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<Elder>();
            lambdaQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
            lambdaQueryWrapper.eq(Elder::getStatus, 1);
            Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
            if (elder != null) {
                log.info("当前老人已入住！");
                throw new BaseException("当前老人已入住！");
            }

            //更新床位状态为已入住（1）
            //根据id找到对应的床位
            Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
            //再将床位状态修改为1
            bed.setBedStatus(1);
            bedMapper.updateById(bed);

            //新增或者更改老人
            Elder elder1 = addOrUpdateElder(dto, bed);

            //新增合同
            //用工具类生成合同编号
            String contractNumber = CodeGenerator.generateContractNumber();
            addContract(dto, contractNumber, elder1);
            //新增入住信息
            CheckIn checkIn = addCheckIn(dto, elder1);

            //新增入住配置
            addCheckInConfig(dto, checkIn);
        } catch (BaseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据入住id查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo selectCheckIndetailById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //添加老人信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Long elderId = checkIn.getElderId();
        //查询老人信息
        Elder elder1 = elderMapper.selectElderById(elderId);
        CheckInElderVo elderVo = new CheckInElderVo();
        //把String类型的信息转换为LocalDate
        LocalDate birthday = LocalDate.parse(elder1.getBirthday());
        elderVo.setAge(LocalDate.now().getYear() - birthday.getYear());
        BeanUtils.copyProperties(elder1, elderVo);
        checkInDetailVo.setCheckInElderVo(elderVo);

        //家庭成员信息
        String remark = checkIn.getRemark();

        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        //入住配置信息
        LambdaQueryWrapper<CheckInConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(lambdaQueryWrapper);
        CheckInConfigVo CheckInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, CheckInConfigVo);
        checkInDetailVo.setCheckInConfigVo(CheckInConfigVo);

        //合同信息
        LambdaQueryWrapper<Contract> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Contract::getElderId, elder1);
        Contract contract = contractMapper.selectOne(lambdaQueryWrapper1);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param dto
     * @param checkIn
     */
    private void addCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        //新增入住配置
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param dto
     * @param elder
     * @return
     */
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), checkIn);

        //补全里面的属性
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        //将老人的家属信息保存
        //将前端传的json数据转换为字符串
        String jsonStr = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(jsonStr);
        log.info("老人的家属{}",jsonStr);
        //根据入住开始结束时间来判断
        Integer status = (dto.getCheckInConfigDto().getStartDate()).isAfter(LocalDateTime.now()) ? 1 : 0;
        checkIn.setStatus(status);

        //保存入住信息
        save(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     *
     * @param
     * @param contractNumber
     * @param elder1
     */
    private void addContract(CheckInApplyDto dto, String contractNumber, Elder elder1) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);

        //添加合同中的老人姓名
        contract.setElderName(elder1.getName());
        contract.setContractNumber(contractNumber);
        contract.setElderId(elder1.getId());
        //设置合同的开始和结束时间
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        //根据入住开始和结束时间来判断当前状态
        Integer status = (dto.getCheckInConfigDto().getStartDate()).isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        //新增合同
        contractMapper.insertContract(contract);
    }

    /**
     * 新增老人信息
     *
     * @param dto
     * @param bed
     * @return
     */
    private Elder addOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        //拷贝老人的基本信息
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        //填充床位编号和床位id
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        //将老人的家属信息保存
        //将前端传的json数据转换为字符串
        String jsonStr = JSONUtil.toJsonStr(dto.getElderFamilyDtoList());
        elder.setRemark(jsonStr);
        //判断老人是否之前住过，以此判断是否新增还是修改
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<Elder>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        lambdaQueryWrapper.eq(Elder::getStatus, 0);
        Elder elder1 = elderMapper.selectOne(lambdaQueryWrapper);
        if (elder1 != null) {
            //修改
            elder.setStatus(1);
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
